/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Servlet;

import donnees.User;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 *
 * @author juge-e
 */
public class SecurityFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        String requestURI = ((HttpServletRequest) request).getRequestURI();

        if (requestURI.equals("/ServerRMI/") || requestURI.equals("/ServerRMI/login.jsp") || requestURI.equals("/ServerRMI/authentification")) {
            chain.doFilter(request, response);
        } else if (requestURI.equals("/ServerRMI/deconnexion.jsp")) {
            ((HttpServletRequest) request).getSession().invalidate();
            request.getRequestDispatcher("/login.jsp").forward(request, response);
        } else {
            verifierSession(request, response);
            chain.doFilter(request, response);
        }

    }

    @Override
    public void destroy() {

    }

    private void verifierSession(ServletRequest request, ServletResponse response) throws ServletException, IOException {

        User user = (User) ((HttpServletRequest) request).getSession().getAttribute("user");
        if (null == user) {
            request.getRequestDispatcher("/erreur.jsp").forward(request, response);
        }

    }
}
